package cn.gzsxt.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter {
	
	//编码字符串
	private String encoding;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//读取编码配置初始化参数
		encoding = filterConfig.getInitParameter("encoding");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//强转子类
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		//获取默认的编码
		String characterEncoding = req.getCharacterEncoding();
		if(characterEncoding == null){
			//设置请求编码
			req.setCharacterEncoding(encoding);
		}
		//放行
		chain.doFilter(req, resp);
	}

	@Override
	public void destroy() {

	}

}
